package com.rich.widget.span

import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.widget.LinearLayout
import android.text.SpannableStringBuilder
import android.text.Spanned

/**
 * 线性渐变效果的具体实现
 */
class LinearGradientFontSpan : FontSpan() {

    /** 文字渐变方向  */
    var textGradientOrientation = GRADIENT_ORIENTATION_HORIZONTAL

    /** 文字渐变颜色组  */
    lateinit var textGradientColor: IntArray

    /** 文字渐变位置组  */
    var textGradientPositions: FloatArray? = null

    override fun onDraw(
        canvas: Canvas,
        paint: Paint,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int
    ) {
        paint.shader =
            if (textGradientOrientation == GRADIENT_ORIENTATION_VERTICAL) LinearGradient(
                0F, 0F, 0F, paint.descent() - paint.ascent(),
                textGradientColor, textGradientPositions, Shader.TileMode.REPEAT
            ) else LinearGradient(
                x, 0F, x + measureTextWidth, 0F,
                textGradientColor, textGradientPositions, Shader.TileMode.REPEAT
            )
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
    }


    companion object {
        /** 水平渐变方向  */
        const val GRADIENT_ORIENTATION_HORIZONTAL = LinearLayout.HORIZONTAL

        /** 垂直渐变方向  */
        const val GRADIENT_ORIENTATION_VERTICAL = LinearLayout.VERTICAL

        /**
         * 构建一个文字渐变色的 Spannable 对象
         */
        fun buildLinearGradientSpannable(
            text: CharSequence?,
            colors: IntArray,
            positions: FloatArray,
            orientation: Int
        ): SpannableStringBuilder {
            val builder = SpannableStringBuilder(text)
            val span = LinearGradientFontSpan().apply {
                textGradientColor = colors
                textGradientOrientation = orientation
                textGradientPositions = positions
            }
            builder.setSpan(span, 0, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            return builder
        }
    }
}

